CUR_PATH=$(dirname $(readlink -f "$0"))
TOP_DIR=${CUR_PATH}/../
SRC_PATH=$1
ARCH=$2
CC=$3

DEFAULT_ARCH=arm64
DEFAULT_COMPILE=aarch64-linux-gnu-

KERNEL_OUT=${SRC_PATH}/output
OUT_RAW=${KERNEL_OUT}/out_raw
DTBTOOL=${SRC_PATH}/scripts/mkdtb.py
KERNEL_DIR=${SRC_PATH}/kernel/linux

CUR_ARCH=`uname -i`

show_help()
{
	echo "Usage:"
	printf "%-60s\n" "	$0 <source path> <ARCH> <CROSS_COMPILE>"
	printf "%-60s %-30s\n" "	$0 ../../source"
	printf "%-60s %-30s\n" "	$0 ../../source arm64 aarch64-linux-gnu-"
	echo "Default:"
	printf "%-60s %-30s\n" "	ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu-"
	exit 1
}

check_para()
{
	if [ ! -d ${KERNEL_DIR} ] || [ ! -d ${SRC_PATH} ]; then
		echo "Check source path Failed: Please check source path!"
		show_help
	fi

	if [ ! ${ARCH} ]; then
		ARCH=${DEFAULT_ARCH}
	fi

	if [ ! ${CC} ];then
		if [[ `uname -i` =~ "aarch" ]]; then
			CC=
		else
			CC=${DEFAULT_COMPILE}
		fi
	fi
}

gen_dtbtool()
{
	if [ ! -e $DTBTOOL ]; then
		gcc -o $DTBTOOL $DTBTOOL_SRC -s -O1
		if [ $? -ne 0 ]; then
			echo "Failed: build dtbTool failed!"
		fi
	fi
}

make_dtb()
{
	echo "Start making dtb"
	KERNEL_AP=$(dirname $(readlink -f "${KERNEL_DIR}/arch"))

	make -C ${CUR_PATH} KERNEL_DIR=${KERNEL_AP} TOP_DIR=${TOP_DIR} ARCH=${ARCH} CROSS_COMPILE=${CC} dtb
	if [ $? -ne 0 ]; then
		return 1
	fi

	python ${DTBTOOL} ${OUT_RAW}/dt_raw.img ${KERNEL_DIR}/scripts/dtc/ ${KERNEL_OUT}/
	if [ $? -ne 0 ]; then
		echo "Failed: execute dtbTool failed!"
		return 1
	fi
}


if [ $# -lt 1 ]; then
	show_help
fi

if [ ! -d ${OUT_RAW} ]; then
	mkdir ${OUT_RAW}
fi

check_para
make_dtb
if [ $? -ne 0 ]; then
	echo "Make dtb failed!"
	exit 1
fi

echo "Make dtb Success!"
exit 0
